<!DOCTYPE html>
<html>

<head>
	<title>Second-Hand Store Login</title>
	<link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>
	<header>
		<h2>UIC Second-Hand Store</h2>
	</header>
	<main>
		<div class="content narrowbox">
			<h2>Login</h2>
			<hr>
			<!--display result-->
			<p class="infotext">
				<?php
				// include the DB connect file 
				include "connectStoreDB.php";

				$user = $_POST["usr"];
				$pwd = $_POST["pwd"];
				$role = $_POST["role"];

				$sql = "SELECT * FROM users WHERE username='$user'"; // query 
				
				$result = $conn->query($sql);

				if ($result->num_rows > 0) {
					//get password from db
					$row = mysqli_fetch_assoc($result);
					$db_pwd = $row['password'];
					$db_usrtype = $row['usertype'];

					//check password
					if ($db_pwd != $pwd) {
						echo "wrong password!";
					} else {
						if ($db_usrtype == "user" && $role == "admin") {
							echo "your account don't have a permission to login as admin!";
						} else {
							echo "login successful!";

							//session to store login status
							session_start();
							$_SESSION['user'] = $user;
							$_SESSION['role'] = $role;

							//redirect to different pages
							switch ($role) {
								case "buyer":
									header("Location: buyer.php");
									break;
								case "seller":
									header("Location: seller.php");
									break;
								case "admin":
									header("Location: adminpage.php");
									break;
							}
						}
					}
				} else {
					echo "no such user, please register first!<br><br>go to <a href='RegisterPage.html'>Register</a>";
				}

				//close connection
				mysqli_close($conn);
				?>
			</p>
			<br>
			<hr>
			<br>
			<p class="infotext">back to <a href="LoginPage.html">Login</a></p>
		</div>
	</main>
</body>

</html>